<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="header">
        <h3>{{ formattedDate }}</h3>
        <el-button type="primary" @click="openDialog('add')">
          <el-icon>
            <Plus/>
          </el-icon>
          新增课程
        </el-button>
      </div>

      <!-- 课程列表表格 -->
      <el-table
        ref="dataTableRef"
        :data="courseList"
        v-loading="loading"
        border
        stripe
        fit
        highlight-current-row
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" align="center"/>
        <el-table-column prop="maxPeople" label="最大人数" align="center"/>
        <el-table-column prop="startTime" label="开始时间" align="center"/>
        <el-table-column prop="endTime" label="结束时间" align="center"/>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">
              <el-icon>
                <Edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteCourse(scope.row.id)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 暂无数据提示 -->
      <div v-if="courseList.length === 0" class="empty-state">
        <el-empty description="暂无课程数据"></el-empty>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="50%"
      @close="handleClose"
    >
      <el-form
        ref="detailFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入课程名称"/>
        </el-form-item>
        <el-form-item label="最大人数" prop="maxPeople">
          <el-input-number
            v-model="formData.maxPeople"
            :min="1"
            :max="100"
            placeholder="请输入最大人数"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-select
            v-model="formData.startTime"
            start="05:30"
            step="00:15"
            end="22:30"
            placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-select
            v-model="formData.endTime"
            start="05:30"
            step="00:15"
            end="22:30"
            placeholder="选择结束时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveCourse">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {deleteFitness, getDetails, insert, update} from "@/api/fitness";
import {useRoute} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';

defineOptions({
  name: 'FitnessDetail', // 与路由配置中的name保持一致
  inherititems: false,
})

const route = useRoute();

// 获取路由参数
const year = route.params.year as string;
const month = route.params.month as string;
const day = route.params.day as string;
//loading
const loading = ref(false);
// 格式化日期显示
const formattedDate = computed(() => `${year}年${month}月${day}日`);

// 课程列表数据
const courseList = ref([]);
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const dialogType = ref('add'); // 'add' 或 'edit'
const detailFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  maxPeople: 10,
  startTime: '',
  endTime: ''
});

// 表单校验规则
const rules = computed(() => {
  return {
    name: [
      {required: true, message: '请输入课程名称', trigger: 'blur'}
    ],
    maxPeople: [
      {required: true, message: '请输入最大人数', trigger: 'blur'},
      {type: 'number', message: '最大人数必须为数字值', trigger: 'blur'}
    ],
    startTime: [
      {required: true, message: '请选择开始时间', trigger: 'change'}
    ],
    endTime: [
      {required: true, message: '请选择结束时间', trigger: 'change'},
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请选择结束时间'));
          } else if (formData.startTime && value <= formData.startTime) {
            callback(new Error('结束时间必须晚于开始时间'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  };
});

// 行样式判断：如果 isDeleted 为 1，返回 'deleted-row' 类
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.isDeleted === 1) {
    return 'deleted-row'; // 对应步骤1中定义的类名
  }
  return ''; // 不满足条件时返回空
};

// 打开对话框
const openDialog = (type: string, row?: any) => {
  dialogType.value = type;
  dialog.title = type === 'add' ? '新增课程' : '编辑课程';
  dialog.visible = true;

  // 延迟重置校验状态
  nextTick(() => {
    detailFormRef.value?.clearValidate(); // 清除校验状态
    if (type === 'edit' && row) {
      // 使用 setFieldsValue 更新（模拟）
      Object.assign(formData, {
        id: row.id,
        name: row.name,
        maxPeople: row.maxPeople,
        startTime: row.startTime,
        endTime: row.endTime
      });
    } else {
      // 新增时初始化为默认值
      Object.assign(formData, {
        id: null,
        name: '',
        maxPeople: 10,
        startTime: '',
        endTime: ''
      });
    }
  });
};

// 关闭对话框
const handleClose = () => {
  dialog.visible = false;
  detailFormRef.value?.resetFields();
  detailFormRef.value?.clearValidate();
};
// 补零函数：确保数字为两位数（如 "7" → "07"，"21" → "21"）
const padZero = (num: string) => {
  return num.padStart(2, '0'); // 用 padStart 补零，不足2位则在前面加"0"
};
// 补零后拼接
const formattedMonth = padZero(month); // "7" → "07"
const formattedDay = padZero(day);     // "21" → "21"（无需补零）
// 保存课程
const saveCourse = () => {
  detailFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;

    // 检查时间段是否重叠
    const isOverlap = checkTimeOverlap(
      formData.startTime,
      formData.endTime,
      formData.id ? formData.id : Date.now()
    );

    if (isOverlap) {
      ElMessage.warning('所选时间段与已有课程冲突');
      return;
    }

    if (dialogType.value === 'add') {
      // 新增课程
      const newCourse = {
        fitnessDate: (Number)(year + formattedMonth + formattedDay),
        ...formData
      };
      insert(newCourse).then(() => {
        handleQuery()
        ElMessage.success('课程添加成功');
      })
    } else {
      // 编辑课程
      const newCourse = {
        ...formData
      };
      update(newCourse).then(() => {
        handleQuery()
        ElMessage.success('课程更新成功');
      })
    }
    dialog.visible = false;
  });
};

// 检查时间段是否重叠
const checkTimeOverlap = (startTime: string, endTime: string, excludeId?: number) => {
  return courseList.value.some(course => {
    // 排除当前编辑的课程
    if (course.id === excludeId) return false;

    // 检查时间是否重叠
    return (
      (startTime < course.endTime && endTime > course.startTime)
    );
  });
};

// 删除课程
const deleteCourse = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除此课程吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteFitness(id).then(()=>{
      handleQuery();
      ElMessage.success('课程删除成功');
    })
  }).catch(() => {
    // 取消操作
  });
};

/** 查询 */
const handleQuery = () => {
  loading.value = true;
  let data = {fitnessDate: (Number)(year + month + day)}
  getDetails(data)
    .then((data) => {
      courseList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 表格行点击事件
const handleRowClick = (row: any) => {
  openDialog('edit', row);
};

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.empty-state {
  padding: 40px 0;
}
::v-deep  .el-table .deleted-row {
  color: red;
  background-color: #fff1f1;
}
</style>
